package com.topscore.uke.ui.fragments;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.topscore.uke.R;
import com.topscore.uke.entities.CommodityData;
import com.topscore.uke.mvp.contractors.GetCommodityPageDataContractor;
import com.topscore.uke.mvp.presenters.GetCommodityPresenter;
import com.topscore.uke.ui.BaseSupportFragment;
import com.topscore.uke.ui.activities.SearchActivity;
import com.topscore.uke.ui.loadsir_callback.EmptyCallBack;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.uke.ui.widgets.DividerItemDecoration;
import com.topscore.uke.utils.SnackBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class CommodityPageFragment extends BaseSupportFragment implements GetCommodityPageDataContractor.View {
    @Bind(R.id.tool_bar)
    Toolbar toolBar;
    @Bind(R.id.recycler_tab)
    RecyclerView recyclerTab;
    @Bind(R.id.commodity_fgm_container)
    FrameLayout commodityFgmContainer;
    @Bind(R.id.search_layout)
    RelativeLayout searchLayout;
    @Bind(R.id.container_layout)
    FrameLayout containerLayout;

    private StuffListFragment mStuffListFragment;

    private FragmentManager mFragmentManager;
    private FragmentTransaction mFragmentTransaction;
    private RecyclerAdapter mAdapter;

    private LoadService mLoadService;
    private ErrorCallBack mErrorCallBack;
    private EmptyCallBack mEmptyCallBack;
    private LoadingCallBack mLoadingCallBack;
    private View rootView;

    private GetCommodityPageDataContractor.Presenter mPresenter = new GetCommodityPresenter(this);

    public CommodityPageFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_commodity_page, container, false);
        ButterKnife.bind(this, rootView);
        initViews();
        return rootView;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search:
                toSearch();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void toSearch() {
        startActivity(new Intent(getContext(), SearchActivity.class));
    }

    private void initViews() {
        initToolBar();
        recyclerTab.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerTab.addItemDecoration(new DividerItemDecoration(getActivity(), R.drawable.white_recycler_divider));
        mAdapter = new RecyclerAdapter();
        recyclerTab.setAdapter(mAdapter);

        searchLayout.setOnClickListener(v -> toSearch());

        initCommodityFragment();
        mErrorCallBack = new ErrorCallBack();
        mEmptyCallBack = new EmptyCallBack();
        mLoadingCallBack = new LoadingCallBack();

        mLoadService = new LoadSir.Builder()
                .addCallback(mLoadingCallBack)
                .addCallback(mErrorCallBack)
                .addCallback(mEmptyCallBack)
                .setDefaultCallback(mLoadingCallBack.getClass())
                .build()
                .register(containerLayout, new Callback.OnReloadListener() {
                    @Override
                    public void onReload(View v) {
                        mPresenter.getCommodityData();
                    }
                });


        initData();
    }

    private void initCommodityFragment() {
        mFragmentManager = getActivity().getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mStuffListFragment = new StuffListFragment();
        mStuffListFragment.setOnBrandSelected(brand -> {

        });
        mFragmentTransaction.add(commodityFgmContainer.getId(), mStuffListFragment).commit();
    }

    private void initData() {
        mPresenter.getCommodityData();
//        List<StuffCategoryBean> beanList = new ArrayList<>();
//        for (int i = 0; i < 15; i++) {
//            StuffCategoryBean bean = new StuffCategoryBean();
//            bean.setId(i);
//            bean.setTitle("标签" + (i + 1));
//            beanList.add(bean);
//        }
//        mAdapter.setNewData(beanList);
    }

    private void initToolBar() {
        setHasOptionsMenu(true);
        toolBar.setTitle("");
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolBar);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu_commodity_search, menu);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onLoading(String loadingMessage) {
//        showProgressDialog(loadingMessage);
        mLoadService.showCallback(LoadingCallBack.class);
    }

    @Override
    public void onLoadFinished() {
//        dismissProgressDialog();
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        mLoadService.showCallback(mErrorCallBack.getClass());
        SnackBarUtil.getInstance(rootView).showShort(errorMessage).show();
    }

    @Override
    public void onGetDataSuccess(List<CommodityData> dataList) {
        if (dataList != null && dataList.size() > 0) {
            dataList.get(0).setSelected(true);
            mStuffListFragment.setUpStuffData(dataList.get(0).getDataList());
            mAdapter.setNewData(dataList);
        } else {
            mEmptyCallBack.setMessage("暂无商品数据");
            mLoadService.showCallback(mEmptyCallBack.getClass());
        }
    }

    private class RecyclerAdapter extends BaseQuickAdapter<CommodityData, BaseViewHolder> {

        public RecyclerAdapter() {
            super(R.layout.commodity_categlory_item, new ArrayList<>());
        }

        @Override
        protected void convert(BaseViewHolder holder, CommodityData item) {
            holder.setText(R.id.item_title, item.getBigclass());
            if (item.isSelected()) {
                holder.getView(R.id.selected_cursor).setVisibility(View.VISIBLE);
                ((TextView) holder.getView(R.id.item_title)).setTextColor(Color.parseColor("#ce3d3e"));
                holder.getConvertView().setBackgroundColor(Color.WHITE);
            } else {
                holder.getView(R.id.selected_cursor).setVisibility(View.GONE);
                ((TextView) holder.getView(R.id.item_title)).setTextColor(Color.parseColor("#333333"));
                holder.getConvertView().setBackgroundColor(Color.TRANSPARENT);
            }

            holder.getConvertView().setOnClickListener(v -> {
                for (int i = 0; i < getData().size(); i++) {
                    getData().get(i).setSelected(false);
                }
                getData().get(holder.getLayoutPosition()).setSelected(true);
                notifyDataSetChanged();
                mStuffListFragment.setUpStuffData(item.getDataList());
            });
        }
    }
}
